/**
 * 弹出提示语
 *
 * @param message 提示语
 * @param success 成功绿 || 失败红
 * @param showTime 显示时间
 */
function showToast(message, success = true, showTime = 2000) {
    const app = document.getElementById('app');
    // 创建Im主窗口
    const toastDiv = document.createElement('div');
    toastDiv.className = success ? 'toastDiv success' : 'toastDiv error';
    toastDiv.innerHTML = message;
    app.appendChild(toastDiv);
    // 2秒后移除弹窗
    setTimeout(function () {
        app.removeChild(toastDiv)
    }, showTime);
}

/**
 * 发送消息
 *
 * @param {Object} message
 */
function sendMessage(message) {
    chrome.runtime.sendMessage(message)
}

/**
 * 防抖函数
 */
function debounce(func, wait, immediate = false) {
    let timeout;
    return function (...args) {
        const context = this;
        const later = () => {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const shouldCallNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (shouldCallNow) func.apply(context, args);
    };
}

// 在当前页面打开链接
function openPage(uri) {
    window.open(uri, '_self');
}

// 在新页面打开链接
function openNewPage(uri) {
    window.open(uri, '_blank');
}

/**
 * fileFile 转 base64
 */
function fileToBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result); // data:image/xxx;base64,...
        reader.onerror = reject;
        reader.readAsDataURL(file);
    })
}

/**
 * 应用壁纸
 */
async function applyBackgroundImage() {
    let userImage = getBackgroundImage()
    if (userImage && userImage !== '') {
        const blob = await (await fetch(userImage)).blob();
        const url = URL.createObjectURL(blob);
        updateCssConfig('--app-background-image', `url(${url})`)
    } else {
        const url = "/src/image/bg.jpg"
        updateCssConfig('--app-background-image', `url(${url})`)
    }
}

/**
 * 导出json文件到指定位置
 *
 * @param data json字符串
 * @param filename 文件名
 * @return {Promise<{success: boolean, message: string}>}
 */
async function exportJsonFile(data, filename = 'data.json') {
    const blob = new Blob([data], {type: 'application/json'});
    try {
        const handle = await window.showSaveFilePicker({
            suggestedName: filename,
            types: [{
                description: 'JSON Files',
                accept: {'application/json': ['.json']}
            }]
        });
        const writable = await handle.createWritable();
        await writable.write(blob);
        await writable.close();
        return {
            success: true,
            message: '导出成功'
        }
    } catch (err) {
        return {
            success: false,
            message: '导出操作取消'
        }
    }
}

/**
 * 导入用户选择的json文件
 *
 * @return {Promise<{success: boolean, data:any, message: string}>}
 */
async function importJsonFile() {
    try {
        const [fileHandle] = await window.showOpenFilePicker({
            types: [{
                description: 'JSON 文件',
                accept: {'application/json': ['.json']}
            }]
        });

        const file = await fileHandle.getFile();
        const content = await file.text();
        const json = JSON.parse(content);
        return {
            success: true,
            data: JSON.stringify(json), // 美化 JSON.stringify(json, null, 2)
            message: '读取成功'
        }
    } catch (err) {
        console.warn('用户取消了选择或读取失败', err);
        return {
            success: false,
            data: null,
            message: '用户取消了选择或读取失败'
        }
    }
}